package com.rgs.module.login.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.rgs.module.login.bo.LoginUserBO;
import com.rgs.module.login.entity.SysUserDO;
import com.rgs.module.login.filter.SysUserFilterDTO;
import com.rgs.module.login.service.SysUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author Ren Gaoshuai
 * @ClassName UserDetailsServiceImpl
 * @Description security 类 验证用户 查数据库对应的username
 * @date 2021-12-24 15:57
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<SysUserDO> sysUserOpt = sysUserService.selectByFilter(SysUserFilterDTO.builder()
                .username(username)
                .build());

        if (!sysUserOpt.isPresent()) {
            System.out.println("登录用户不存在");
        }

        SysUserDO sysUser = sysUserOpt.get();
        return LoginUserBO.builder()
                .username(username)
                .userId(sysUser.getId())
                .isAdmin(false)
                .otherInfo(BeanUtil.beanToMap(sysUser))
                .password(sysUser.getPassword())
                .build();
    }
}
